﻿<template>
  <section class="auth-view">
    <ElCard class="auth-card">
      <template #header>
        <div class="header">
          <h2>创建账号</h2>
          <RouterLink to="/login">已有账号？前往登录</RouterLink>
        </div>
      </template>
      <ElForm :model="form" :rules="rules" ref="formRef" label-position="top">
        <ElFormItem label="昵称" prop="name">
          <ElInput v-model="form.name" placeholder="请输入昵称" />
        </ElFormItem>
        <ElFormItem label="邮箱" prop="email">
          <ElInput v-model="form.email" placeholder="you@mint.com" autocomplete="email" />
        </ElFormItem>
        <ElFormItem label="密码" prop="password">
          <ElInput
            v-model="form.password"
            type="password"
            placeholder="不少于 6 位"
            autocomplete="new-password"
          />
        </ElFormItem>
        <ElAlert
          v-if="authError"
          type="error"
          :closable="false"
          class="auth-alert"
          show-icon
        >
          {{ authError }}
        </ElAlert>
        <ElButton
          type="primary"
          class="submit"
          :loading="authStore.loading"
          @click="onSubmit"
        >
          注册并登录
        </ElButton>
      </ElForm>
    </ElCard>
  </section>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect, computed } from "vue";
import { useRouter, RouterLink } from "vue-router";
import { ElForm, ElFormItem, ElInput, ElButton, ElCard, ElAlert, type FormInstance } from "element-plus";
import { useAuthStore } from "../stores/auth";

const authStore = useAuthStore();
const router = useRouter();
const formRef = ref<FormInstance>();

const form = reactive({
  name: "",
  email: "",
  password: "",
});

const rules = {
  name: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "邮箱格式不正确", trigger: "change" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码至少 6 位", trigger: "blur" },
  ],
};

const authError = computed(() => authStore.error);

const onSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    await authStore.register({ ...form });
    router.push({ name: "profile" });
  } catch (error) {
    // 错误在 store 中统一处理
  }
};

watchEffect(() => {
  if (authStore.isAuthenticated) {
    router.push({ name: "profile" });
  }
});
</script>

<style scoped>
.auth-view {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 70vh;
}

.auth-card {
  width: min(460px, 90vw);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.submit {
  width: 100%;
}

.auth-alert {
  margin-bottom: 16px;
}
</style>
